<template>
  <div class="modal fade" id="batchSaveModal" tabindex="-1" role="dialog" data-backdrop="static"  aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content" style="width: 760px;font-size: 15px;">
        <div class="modal-header">
          <!--<button type="button" :disabled="!percent ==100 || progressShow" class="close" @click="canel"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>-->
          <h4 class="modal-title" id="myModalLabel">客户基本信息（批量报备）</h4>
        </div>
        <div class="modal-body form-horizontal">
          <div class="" v-if="!progressShow">
            <div class="row form-group">
              <div class="col-md-6" >
                <label class="col-md-3 label-header control-label"><span style="color: #cc0837;">*</span>意向楼盘</label>
                <div class="col-md-9" style="padding-left: 0;width: 200px;">
                  <select name="quiz1" class="layui-input" id="state" v-model="params.premisesId" v-on:change="changeTemp(params.premisesId)">
                    <option value="">请选择</option>
                    <option v-for="premises in PremisesGroupByCityList"   :value="premises.premisesId" >{{premises.premisesName}}</option>
                  </select>
                </div>
              </div>
              <div class="col-md-6">
                <label class="col-md-3 label-header control-label"><span style="color: #cc0837;">*</span>期望带看时间</label>
                <div class="col-md-9" style="padding-left: 0;width: 200px;">
                  <DatePicker type="datetime" v-model="params.visitProtectDate"  format="yyyy-MM-dd HH:mm"></DatePicker>
                </div>
              </div>
              <li class="col-sm-12 col-md-6">
                <label class="col-md-3 label-header control-label">报备推荐人</label>
                <recommend-select
                    :premises-id="params.premisesId"
                    v-model="params.recommenderUuid"/>
              </li>
            </div>
            <div class="row form-group">
              <div class="col-md-12" >
                <label class="col-md-3 label-header control-label"><span style="color: #cc0837;">*</span>备注</label>
                <div class="col-md-9" style="padding-left: 0;width: 580px;">
                  <textarea v-model="params.remark" placeholder="请输入内容" class="layui-textarea" style="height: 135px;"></textarea>
                </div>
              </div>
            </div>

            <div class="layui-form-item layui-form-text">
              <label class="layui-form-label control-label"></label>
              <div class="layui-input-inline" style="width: 380px;">
                <input type="text" readonly v-model="fileNameVal" class="layui-input" style="float: left;width: 230px;">
                <label for="fileName"
                       style="width: 120px;height: 37px; font-size: 13px; font-weight: 400;
                    line-height: 37px;background-color: #0099cc;
                    color: #FFFFFF;text-align: center;
                    margin: 0 0 0 20px;border-radius: 3px;">批量导入客户名单</label>
                <input type="file" class="form-control" @change="onFileChange" name="fileName" id="fileName" style="display: none;">
              </div>
              <a v-if="hasErrorRecord" class="layui-form-label control-label" style="color: #0099cc;font-size: 16px;width: 115px;padding-left: 0;padding-right: 0;" :href="downloadErrorUrl">错误信息下载</a>
            </div>

            <div class="layui-form-item layui-form-text">
              <div class="row form-group">
                <div class="col-md-12">
                  <label style="color: #E88037; font-size: 13px; margin-left: 60px; font-weight: 400;">*若您还没有填写模板，请先下载模板进行填写</label>
                </div>
              </div>
              <div class="row form-group">
                <div class="col-md-6" v-if="reportWay === '0' || reportWay === '1'">
                  <div class="col-md-2" style="padding-left: 0; margin-left: 60px;">
                    <img src="../../assets/images/excel_01.png" style="width: 38px; height: 43px;" alt="">
                  </div>
                  <div class="col-md-3" style="padding-left: 0;  width: 200px;">
                    <div style="float: left;">
                      <label style="color: #E88037; font-size: 14px; font-weight: 400;">
                        <a :href="downloadWholeTempUrl">显号导入模板下载</a>
                      </label>
                    </div>
                    <div style="float: left;">
                      <label style="color: #CCC; font-size: 12px; font-weight: 400;">仅能用于显号批量报备</label>
                    </div>
                  </div>
                </div>
                <div class="col-md-6" v-if="reportWay!=='1'">
                  <div class="col-md-2" :style="{'margin-left': (reportWay === '0' || reportWay === '1')? '0px':'60px','padding-left': 0}">
                    <img src="../../assets/images/excel_02.png" style="width: 38px; height: 43px;" alt="">
                  </div>
                  <div class="col-md-3" style="padding-left: 0; width: 200px;">
                    <div style="float: left; color: #E88037;">
                      <label style="color: #E88037; font-size: 14px; font-weight: 400;">
                        <a :href="downloadHide34TempUrl" v-show="reportWay === '0' || reportWay === '2'">隐号导入模板下载(前三后四)</a>
                        <a :href="downloadHide43TempUrl" v-show="reportWay === '3'">隐号导入模板下载(前四后三)</a>
                        <a :href="downloadHide35TempUrl" v-show="reportWay === '4'">隐号导入模板下载(前三后五)</a>
                        <a :href="downloadHide26TempUrl" v-show="reportWay === '5'">隐号导入模板下载(前二后六)</a>
                        <a :href="downloadHide44TempUrl" v-show="reportWay === '6'">隐号导入模板下载(前四后四)</a>
                      </label>
                    </div>
                    <div style="float: left;">
                      <label style="color: #CCC; font-size: 12px; font-weight: 400;">仅能用于隐号批量报备</label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="" v-if="progressShow">
            <!--<Progress stroke-width="25" stroke-color="#19be6b" :percent="percent" status="active" />-->
            <div class="progress-back">
              <div class="progress-front" id="progressFront"></div>
            </div>
            <div>
              <div class="total-msg">导入总数：<span id="total"></span>，成功：<span id="success"></span> 条，失败：<span id="fail"></span>条。</div>
              <ul class="error-msg"  id="errormsg">
                <!--<li v-for="(m,index) in errorMsgs"><span class="error-num">{{index+1}}</span> &nbsp&nbsp经纪人：{{m.report.agentName}}，手机号：{{m.report.agentPhone}}，客户：{{m.report.name}}，手机号：{{m.report.mobile}}<span style="color:#ff4949">&nbsp{{m.error}}</span></li>-->
              </ul>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <label v-if="reportWay==='1'" style="color: #2d2d2d; font-size: 14px; font-weight: 400; margin-right:5px;"><Icon type="ios-alert" color="#E88037"/>该楼盘仅支持全号报备</label>
          <label v-if="reportWay!=='0' && reportWay!=='1'" style="color: #2d2d2d; font-size: 14px; font-weight: 400; margin-right:5px;"><Icon type="ios-alert" color="#E88037"/>该楼盘仅支持隐号报备</label>
          <button type="button" class="btn btn-theme" @click="batchSave" v-if="!progressShow">报备</button>
          <button type="button" class="btn btn-default" @click="canel" v-if="!progressShow">取消</button>
          <button type="button" id="returnBtn" class="btn btn-theme" :disabled="percent!=100"  @click="goBack" v-if="progressShow">返回</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { formatDate } from '../../assets/js/date.js'
  import RecommendSelect from "./components/RecommendSelect.vue"
  export default {
    components: {
      RecommendSelect,
    },
    data() {
      return {
          PremisesGroupByCityList: [],
          reportWay:'0',
          downloadWholeTempUrl: this.utilHelper.importCuspreWholeTempUrl,
          downloadHide34TempUrl: this.utilHelper.importCuspreHide34TempUrl,
          downloadHide43TempUrl: this.utilHelper.importCuspreHide43TempUrl,
          downloadHide35TempUrl: this.utilHelper.importCuspreHide35TempUrl,
          downloadHide26TempUrl: this.utilHelper.importCuspreHide26TempUrl,
          downloadHide44TempUrl: this.utilHelper.importCuspreHide44TempUrl,
          fileUrl: '',
          fileNameVal: '',
          userId: window.localStorage.getItem("4_userId"),
          params: {
              premisesId: '',
              remark: '',
              batchId: '',
              visitProtectDate: '',
            recommenderUuid: ''
          },
          hasErrorRecord: false,
          downloadErrorUrl: '',
          progressShow:false,
          socket:"",
          errorMsgs:[],
          percent:0,
          importTotal:0,
          importSuccess:0,
          importFail:0,
          lockReconnect:false,
          heartCheck: {
              timeout : 10000,       //9分钟发一次心跳
              timeoutObj : null,
              serverTimeoutObj : null,
              reset:function(){
                  clearTimeout(this.timeoutObj);
                  clearTimeout(this.serverTimeoutObj);
                  return this;
              },
              start:function(object) {
                  var self = this;
                  this.timeoutObj = setTimeout(function () {
                      //这里发送一个心跳，后端收到后，返回一个心跳消息，
                      //onmessage拿到返回的心跳就说明连接正常
                      object.socket.send("ping");
                      this.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置，说明后端主动断开了
                         if(object.socket.readyState !=3){
                             object.socket.close();     //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                         }

                      }, this.timeout)
                  }, this.timeout)
              }
          },
      };
    },
    mounted: function() {
        var _self =this;
        setTimeout(() => {
          this.initPremisesInfo();
        }, 500)
        $('input[name=looktime]').datetimepicker({
            format: 'yyyy-mm-dd HH:mm',
            autoclose: true,
            minView:2
        });
        window.onload= () => {
            _self.dataInit();
        }
        // _self.initWebsocket();
    },
    methods: {
        initPremisesInfo:function(){
            var url = this.utilHelper.apiUrl+'/api/getPremisesGroupByCity.do';
            var body = {};
            body.params = {};
            this.$http.post(url,body).then((response)=>{
                var body = response.body;
                if(body.result==1 && body.resData.list && body.resData.list.length > 0){
                    for (let obj of body.resData.list) {
                        if(obj && obj.preGroupByCityList) {
                          let premisesList = obj.preGroupByCityList;
                          for (let premisesInfo of premisesList) {
                            this.PremisesGroupByCityList.push(premisesInfo);
                          }
                        }
                    }
                }else{
                    layer.msg("数据获取失败");
                }

            });
        },
        onFileChange(e) {
          var files = e.target.files || e.dataTransfer.files;
          if (!files.length)
              return;
          this.fileNameVal = files[0].name;
          this.createFile(files[0]);
        },
        createFile(file) {
            var _self = this;
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function(e){
                _self.fileUrl = e.target.result;
                _self.ajaxfile();
            };
        },
        //将base64转换blob
        dataURLtoBlob(dataUrl) {
            var arr = dataUrl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        },
        vilidate () {
          if(!this.params.premisesId) {
              layer.msg('请选择意向楼盘！');return;
          }
          if(!this.params.visitProtectDate) {
              layer.msg('请选择期望带看时间！');return;
          }
          if(!this.params.remark) {
              layer.msg('请填写备注！');return;
          }
          if(!this.params.batchId) {
              layer.msg('请选择Excel文件！');return;
          }
          return true;
        },
        batchSave () {
            var _self = this;

            if(!this.vilidate()) {
                return;
            }
            //_self.progressShow = true;
            _self.errorMsgs = [];
            this.importTotal=0;
            this.importSuccess=0;
            this.importFail=0;
            var reqData={
                userId: _self.userId,
                premisesId: _self.params.premisesId,
                remark: _self.params.remark,
                batchId: _self.params.batchId,
              recommenderUuid: _self.params.recommenderUuid,
                visitProtectDate: formatDate(_self.params.visitProtectDate,'yyyy-MM-dd hh:mm')
            }
            var body = {};
            body.params = reqData;
            var url = this.utilHelper.apiUrl+'/api/addBatchCusPre';
            var loadIndex = layer.load(0); //弹出加载层
            _self.$http.post(url,body,{timeout:0}).then((response)=>{
                layer.close(loadIndex); //关闭加载层
                var body = response.body;
                if(body.result=="1"){
                    this.hasErrorRecord = body.resData.hasErrorRecord;
                    /*
                     layer.confirm("提交成功，请实时查看报备列表！", {
                            closeBtn: false,
                            btn: ['确认']
                        }, function(index){
                            layer.close(index);
                     });
                     */
                     if(this.hasErrorRecord) {
                         layer.confirm(body.resData.showMsg, {
                             closeBtn: false,
                             btn: ['确认']
                         }, function(index){
                             layer.close(index);
                         });
                      this.downloadErrorUrl = this.utilHelper.apiUrl + '/api/exportBatchImpError?params.userId='+this.userId+'&params.batchId='+this.params.batchId
                     } else {
                         layer.confirm(body.resData.showMsg, {
                             closeBtn: false,
                             btn: ['确认']
                         }, function(index){
                             layer.close(index);
                             _self.canel();
                         });
                     }

                }else{
                    layer.open({
                        content: body.errorMsg
                    });
                }
            },(response)=>{
                console.log(response);
                layer.alert("请求异常!");
            });
        },
        validate () {
        },
        //上传excel
        ajaxfile(){
            var _self = this;
            if(_self.fileUrl == null || _self.fileUrl == ""){
                layer.msg("请选择需要导入的excel");
                return false;
            }
            var fileName = $("#fileName").val();
            var suffix = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length);
            if(suffix != "xls" && suffix != "xlsx"){
                layer.msg("请选择正确的excel");
                return false;
            }

            $('#fileName').replaceWith('<input type="file" name="fileName" id="fileName" style="display: none;">');
            $('#fileName').on('change', function (e) {
                _self.onFileChange(e);
            });

            var myForm = new FormData();     //创建formdata
            var blobBin = _self.dataURLtoBlob(_self.fileUrl);   //base64转换blob
            myForm.append(suffix, blobBin);    //向formData添加blob数据
            myForm.append("userId", _self.userId);
            var url = _self.utilHelper.apiUrl+'/api/importCusPre';
            layer.load(0, {shade: false}); //弹出加载层
            _self.$http.post(url,myForm).then((response)=>{
                layer.closeAll('loading'); //关闭加载层
                var data = response.body;
                if(data.result == "1"){
                    //子组件向父组件传递信号: 调用父组件中对子组件的监听
                    if(data.resData != null){
                        _self.params.batchId = data.resData;
                    } else {
                        layer.msg(data.errorMsg, {
                            time: 4000
                        });
                    }
                } else {
                  layer.msg(data.errorMsg, {
                      time: 4000
                  });
                }
            });
        },
        canel: function() {
            this.fileUrl = '';
            this.fileNameVal = '';
            this.params.premisesId = '';
            this.params.remark = '';
            this.params.batchId = '';
            this.params.visitProtectDate = '';
            this.hasErrorRecord = false;
            this.downloadErrorUrl = '';
          $("#batchSaveModal").modal("hide");
            //子组件向父组件传递信号: 调用父组件中对子组件的监听
            this.$emit('batchSaveListener');
            this.progressShow = false;
            this.percent=0;
        },
        //websocket
        initWebsocket: function () {
            if(typeof(WebSocket) === "undefined"){
                alert("您的浏览器不支持消息推送")
            }else{
                // 实例化socket
                this.socket = new WebSocket(this.utilHelper.wsUrl+"?uid="+this.userId);
                // 监听socket连接
                this.socket.onopen = this.open
                // 监听socket错误信息
                this.socket.onerror = this.error
                // 监听socket消息
                this.socket.onmessage = this.getMessage
                //监听socket关闭状态
                this.socket.onclose=this.close;
            }
        },
        open: function () {
            console.log("socket连接成功")
            // this.heartCheck.reset().start(this);
            var _self = this;
            window.setInterval(function(){ //每隔5秒钟发送一次心跳，避免websocket连接因超时而自动断开
                _self.socket.send('ping');
            },21000);
        },
        error: function () {
            this.reconnect();
            console.log("连接错误")
        },
        getMessage: function (msg) {
            // this.heartCheck.reset().start(this);
            if(msg.data == 'pong'){
                console.log('pong ==============>' + data );
                return;
            }
            let data = JSON.parse(msg.data);
            this.importTotal=data.total;
            this.importSuccess=data.currentSuccess;
            this.importFail=data.currentFail;
            document.getElementById("total").innerHTML = data.total;
            document.getElementById("success").innerHTML = data.currentSuccess;
            document.getElementById("fail").innerHTML = data.currentFail;
            if(data.success == false){
                let limsg = '<li ><span class="error-num"></span> &nbsp&nbsp经纪人：'+data.report.agentName+'，手机号：'+data.report.agentPhone+'，客户：'+data.report.name+'，手机号：'+data.report.mobile+'<span style="color:#ff4949">&nbsp'+data.error+'</span></li>'
                let subNode = document.createElement("li");
                subNode.innerHTML = limsg;
                document.getElementById("errormsg").appendChild(subNode);
            }

            //进度条
            document.getElementById("progressFront").style.width= data.percent +'%';

            if(data.currentFail > 0){
                // this.errorMsgs.push(data);
                document.getElementById("errormsg").style.display='block';
            }
            if(data.percent == 100){
              document.getElementById("returnBtn").disabled = false;
            }

            this.percent = data.percent;
        },
        send: function (msg) {
            this.socket.send(msg)
        },
        close: function () {
            console.log("socket已经关闭");
            this.reconnect();
        },
        destroyed () {
          // 销毁监听
          this.socket.onclose = this.close
        },
        reconnect() {
            console.log('reconnecting...')
            var _self = this;
            if(_self.lockReconnect) return;
            _self.lockReconnect = true;
            setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
                _self.initWebsocket();
                _self.lockReconnect = false;
            }, 2000);
        },
        goBack(){
            this.dataInit();
        },
        dataInit(){
            var _self = this;
            _self.progressShow=false;
            _self.percent=0;
            //清理数据，总数，失败，成功置位0;
            const $ = function (id) {
              if (!id) return false
              return document.getElementById(id)
            }
            if($('success') && $('success').innerHTML){
                document.getElementById("success").innerHTML = 0;
            }
            if($('fail') && $('fail').innerHTML){
                document.getElementById("fail").innerHTML = 0;
            }
            if($('total') && $('total').innerHTML){
                document.getElementById("total").innerHTML = 0;
            }
            if($('errormsg') && $('errormsg').innerHTML){
                //清空错误信息
                document.getElementById("errormsg").innerHTML='';
            }
            if($('errormsg')) $('errormsg').style.display='none';
            //进度条回归
            if($('progressFront')) $('progressFront').style.width= 0;

        },
        changeTemp(premisesId){
            for(let premises of this.PremisesGroupByCityList){
               if(premises.premisesId === premisesId){
                 if(premises.reportWay){
                   this.reportWay = premises.reportWay;
                 }else{
                   this.reportWay = '0';
                 }
               }
            }
        },

    }
  };
</script>

<style scoped>
  .modal-footer {
    padding: 20px 30px 20px 20px;
    text-align: right !important;
    border-top-style: none !important;
    background-color: #FFFFFF !important;
  }
  .control-label {
    float: left;
    display: block;
    padding: 9px 15px;
    width: 130px;
    font-weight: 400;
    text-align: right;
  }
  .error-msg{max-height: 400px;overflow-y: auto;border:1px solid #bcbcbc;border-radius: 5px;padding: 5px;font-size: 14px;}
  .total-msg{margin: 10px 0;font-weight: 800;font-size:14px;}
  .error-num{width: 20px;display: inline-block;}
  .progress-back{position: relative;width: 730px;height: 25px;background: #dddddd;}
  .progress-front{position: absolute;height: 25px;background: #00B83F;top:0;left:0;}
  #errormsg{display: none;}
</style>
